// 性能优化工具类
export class PerformanceUtils {
  static frameCount = 0
  static lastTime = 0
  static fps = 60

  // 初始化性能监控
  static init() {
    this.lastTime = performance.now()
    this.startFPSMonitoring()
  }

  // 开始FPS监控
  static startFPSMonitoring() {
    const updateFPS = () => {
      const currentTime = performance.now()
      this.frameCount++
      
      if (currentTime - this.lastTime >= 1000) {
        this.fps = Math.round((this.frameCount * 1000) / (currentTime - this.lastTime))
        this.frameCount = 0
        this.lastTime = currentTime
        
        // 如果FPS过低，输出警告
        if (this.fps < 30) {
          console.warn(`Low FPS detected: ${this.fps}`)
        }
      }
      
      requestAnimationFrame(updateFPS)
    }
    
    requestAnimationFrame(updateFPS)
  }

  // 获取当前FPS
  static getFPS(): number {
    return this.fps
  }

  // 防抖函数 - 防止频繁调用
  static debounce<T extends (...args) => any>(
    func,
    wait): (...args) => void {
    let timeout: NodeJS.Timeout | null = null
    
    return (...args) => {
      if (timeout) {
        clearTimeout(timeout)
      }
      
      timeout = setTimeout(() => {
        func.apply(null, args)
      }, wait)
    }
  }

  // 节流函数 - 限制调用频率
  static throttle<T extends (...args) => any>(
    func,
    limit): (...args) => void {
    let inThrottle = false
    
    return (...args) => {
      if (!inThrottle) {
        func.apply(null, args)
        inThrottle = true
        setTimeout(() => inThrottle = false, limit)
      }
    }
  }

  // 对象池 - 重用游戏对象以减少垃圾回收
  static createObjectPool<T>(
    createFn: () => T,
    resetFn: (obj) => void,
    initialSize= 10
  ) {
    const pool= []
    const active= new Set()

    // 预创建对象
    for (let i = 0; i < initialSize; i++) {
      pool.push(createFn())
    }

    return {
      get(): T {
        let obj = pool.pop()
        if (!obj) {
          obj = createFn()
        }
        active.add(obj)
        return obj
      },

      release(obj) {
        if (active.has(obj)) {
          active.delete(obj)
          resetFn(obj)
          pool.push(obj)
        }
      },

      clear() {
        active.clear()
        pool.length = 0
      },

      getActiveCount(): number {
        return active.size
      },

      getPoolSize(): number {
        return pool.length
      }
    }
  }

  // 内存使用监控
  static getMemoryUsage(): { used, total, percentage: number } | null {
    if ('memory' in performance) {
      const memory = (performance as any).memory
      return {
        used: Math.round(memory.usedJSHeapSize / 1024 / 1024), // MB
        total: Math.round(memory.totalJSHeapSize / 1024 / 1024), // MB
        percentage: Math.round((memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100)
      }
    }
    return null
  }

  // 批量处理 - 将大量操作分批执行以避免阻塞
  static async batchProcess<T>(
    items,
    processor: (item) => void | Promise<void>,
    batchSize= 10,
    delay= 0
  ): Promise<void> {
    for (let i = 0; i < items.length; i += batchSize) {
      const batch = items.slice(i, i + batchSize)
      
      await Promise.all(batch.map(processor))
      
      if (delay > 0 && i + batchSize < items.length) {
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }
  }

  // 检查设备性能等级
  static getDevicePerformanceLevel(): 'high' | 'medium' | 'low' {
    const canvas = document.createElement('canvas')
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl')
    
    if (!gl) return 'low'
    
    const renderer = gl.getParameter(gl.RENDERER)
    const vendor = gl.getParameter(gl.VENDOR)
    
    // 简单的性能评估
    const cores = navigator.hardwareConcurrency || 2
    const memory = (navigator as any).deviceMemory || 2
    
    if (cores >= 8 && memory >= 8) return 'high'
    if (cores >= 4 && memory >= 4) return 'medium'
    return 'low'
  }

  // 根据设备性能调整游戏设置
  static getOptimalSettings(): {
    particleCount: number
    animationQuality: 'high' | 'medium' | 'low'
    enableEffects: boolean
    targetFPS: number
  } {
    const level = this.getDevicePerformanceLevel()
    
    switch (level) {
      case 'high':
        return {
          particleCount: 50,
          animationQuality: 'high',
          enableEffects,
          targetFPS: 60
        }
      case 'medium':
        return {
          particleCount: 25,
          animationQuality: 'medium',
          enableEffects,
          targetFPS: 30
        }
      case 'low':
        return {
          particleCount: 10,
          animationQuality: 'low',
          enableEffects,
          targetFPS: 30
        }
    }
  }

  // 清理未使用的资源
  static cleanupResources(scene: Phaser.Scene) {
    // 清理未使用的纹理
    const textureManager = scene.textures
    const usedTextures = new Set<string>()
    
    // 收集正在使用的纹理
    scene.children.list.forEach((child) => {
      if (child.texture && child.texture.key) {
        usedTextures.add(child.texture.key)
      }
    })
    
    // 移除未使用的纹理
    textureManager.list.forEach((texture, key) => {
      if (!usedTextures.has(key) && !key.startsWith('__')) {
        textureManager.remove(key)
      }
    })
    
    // 强制垃圾回收（如果可用）
    if ('gc' in window) {
      (window as any).gc()
    }
  }

  // 性能统计报告
  static getPerformanceReport(): string {
    const memory = this.getMemoryUsage()
    const level = this.getDevicePerformanceLevel()
    const settings = this.getOptimalSettings()
    
    return `
性能报告:
- FPS: ${this.getFPS()}
- 设备性能等级: ${level}
- 内存使用: ${memory ? `${memory.used}MB / ${memory.total}MB (${memory.percentage}%)` : '不可用'}
- 推荐设置: 粒子数量 ${settings.particleCount}, 动画质量 ${settings.animationQuality}
- 硬件并发: ${navigator.hardwareConcurrency || '未知'}
- 用户代理: ${navigator.userAgent.substring(0, 50)}...
    `.trim()
  }
}
